<template>
  <div class="app-container">
    <div class="class-table">
      <!-- 下拉选择学期 -->
      <el-select
        class="semester-select"
        v-model="semesterId"
        placeholder="请选择学期"
        @change="changeSemester"
      >
        <el-option
          v-for="(item, index) in semesterData"
          :key="index"
          :value="item.id"
          :label="item.semesterName"
        ></el-option>
      </el-select>
      <!-- 下拉选择班级 -->
      <el-select
        class="class-select"
        @change="handleSelectClass"
        @clear="clearListener"
        clearable
        v-model="classNo"
        placeholder="请选择班级"
      >
        <el-option
          v-for="(item, index) in classData"
          :key="index"
          :value="item.classNo"
          :label="item.className"
        ></el-option>
      </el-select>
      <el-select
        class="class-select"
        @change="handleSelectRoom"
        @clear="clearListener"
        clearable
        v-model="roomNo"
        placeholder="请选择教室"
      >
        <el-option
          v-for="(item, index) in roomData"
          :key="index"
          :value="item.roomNo"
          :label="item.roomName"
        ></el-option>
      </el-select>
      <el-select
        class="class-select"
        @change="handleSelectTeacher"
        @clear="clearListener"
        clearable
        v-model="teacherNo"
        placeholder="请选择教师"
      >
        <el-option
          v-for="(item, index) in teacherData"
          :key="index"
          :value="item.teacherNo"
          :label="item.teacherName"
        ></el-option>
      </el-select>
      <div style="width: 10px; display: inline-block"></div>
      <el-button
        type="primary"
        @click="adjustConfirm"
        :disabled="srcId == null || destTimeslot == -1"
      >
        手动处理排课
      </el-button>
      <el-button
        :type="chooseType == 0 ? 'success' : 'primary'"
        @click="chooseType = !chooseType"
      >
        选择{{ chooseType == 0 ? "目的时间" : "待移动课" }}
      </el-button>
    </div>
    <br />
    <el-table
      :data="classTableData.lessons"
      border
      style="width: 100%"
      id="my-table"
      @cell-click="click"
    >
      <!-- 时间列 -->
      <el-table-column prop="name" label="时间" width="100" align="center">
        <template slot-scope="scope">
          <p>{{ digital2Chinese(scope.$index + 1) }}</p>
          <p class="period">{{ scope.row }}</p>
        </template>
      </el-table-column>

      <!-- 周次和课程信息列 -->
      <el-table-column
        v-for="(weekNum, weekIndex) in classTableData.courses"
        :key="weekIndex"
        :label="'周' + digital2Chinese(weekIndex + 1, 'week')"
        width="170"
        header-align="center"
        :index="weekIndex"
      >
        <template slot-scope="scope">
          <div
            class="course-info"
            :timeslot="classTableData.timeslot[weekIndex][scope.$index]"
            :row="scope.$index"
            :col="weekIndex"
          >
            <span
              class="span"
              style="background-color: lightgreen"
              v-if="destRow == scope.$index && destCol == weekIndex"
            >
              目的时间
            </span>

            <span
              class="span"
              style="background-color: rgb(241, 253, 241); color:gray"
              v-if="inRecommendDest(weekIndex, scope.$index)"
            >
              推荐目的时间
            </span>

            <div
              @click="clickCard"
              v-for="(t, i) in convertMsgToList(
                classTableData.courses[weekIndex][scope.$index]
              )"
              class="mycard"
            >
              <span
                :timetableid="
                  convertIdToList(
                    classTableData.timetableId[weekIndex][scope.$index]
                  )[i]
                "
                :timeslot="classTableData.timeslot[weekIndex][scope.$index]"
                :row="scope.$index"
                :col="weekIndex"
                class="span"
                style="background-color: blue"
                v-show="
                  convertIdToList(
                    classTableData.timetableId[weekIndex][scope.$index]
                  )[i] == srcId
                "
              >
                待移动课
              </span>
              {{ t }}
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        2: "success",
        0: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      chooseType: 0,
      classData: [],
      roomData: [],
      teacherData: [],
      semesterData: [],
      classNo: "",
      roomNo: "",
      teacherNo: "",
      semesterId: "",
      list: null,
      listLoading: true,
      search: "",
      total: 0,
      currentPage: 1,
      currentIndex: "",
      pagesize: 10,
      classTableData: {
        lessons: [
          "08.20-09.55",
          "10.15-11.50",
          "14.20-15.55",
          "16.15-17.50",
          "18.30-20.05",
        ],
        courses: [[], [], [], [], [], [], []],
        timetableId: [[], [], [], [], [], [], []],
        timeslot: [[], [], [], [], [], [], []],
      },
      recommendDest: [],
      srcId: null,
      srcRow: -1,
      srcCol: -1,
      srcTimeslot: -1,
      destId: null,
      destRow: -1,
      destCol: -1,
      destTimeslot: -1,
    };
  },
  created() {
    this.getList();
    this.getSemester();
    this.getClass();
    this.getRoom();
    this.getTeacher();
  },
  mounted() {
    // 先create后mouted
    let id = this.$store.getters.getSemesterId;
    this.semesterId = id;
  },
  methods: {
    changeSemester() {
      this.clearListener()
      this.clearAdjustPick()
      this.getList();
    },
    test() {
      console.log(this.classTableData);
      console.log("init", this.classTableDataInit);
    },
    inRecommendDest(week, i) {
      if(this.recommendDest.length==0) return false
      let timeslot = week*5 + i
      for(let key in this.recommendDest) {
        if (this.recommendDest[key] == timeslot) return true
      }

      return false
    },
    clickCard(event) {
      if (this.chooseType != 0) return;
      var node = event.target.firstElementChild;

      var id = node.getAttribute("timetableid");
      var row = node.getAttribute("row");
      var col = node.getAttribute("col");
      var timeslot = node.getAttribute("timeslot");

      if (id == null || id == -1 || id == "") return;
      if (this.srcId == id) {
        this.clearAdjustPick();
        return;
      }
      this.srcRow = row;
      this.srcCol = col;
      this.srcId = id;
      this.srcTimeslot = timeslot;

      // // 查看与本id有冲突的个体
      this.getConfilctList(id);
      // // 排练
      this.rehearsalChangeTimeslot(id);
    },
    convertIdToList(id) {
      if (!id) return [""];
      let list = id.split("@@@");
      return list;
    },
    convertMsgToList(msg) {
      if (!msg) return [];
      let list = msg.split("@@@");
      return list;
    },
    click(trash1, trash2, cell, event) {
      if (this.chooseType != 1) return;

      var node = cell.firstElementChild.firstElementChild;
      var row = node.getAttribute("row");
      var col = node.getAttribute("col");
      var timeslot = node.getAttribute("timeslot");
      if (this.destRow == row && this.destCol == col) {
        
        this.clearAdjustPick()
        return
      }
      if (this.srcRow == row && this.srcCol == col) {
        this.$message.error("待移动课和目的时间不能在同个时间块");
      } else {
        this.recommendDest = []
        this.destRow = row;
        this.destCol = col;
        this.destTimeslot = timeslot;
      }
    },
    adjustConfirm() {
      var that = this;
      var srcId = this.srcId;
      var destTimeslot = this.destTimeslot;
      this.$confirm(
        "将把" + srcId + "调到" + this.timeslotConvert(destTimeslot) + "?",
        "手动调课",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          that.adjust(srcId, destTimeslot);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    adjust(srcId, destTimeslot) {
      this.$axios
        .put("/timetable/adjust/" + srcId + "/" + destTimeslot, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          this.$message.info(res.data.msg);
          this.clearAdjustPick();

          if (this.classNo != "") {
            this.queryClass();
          } else if (this.roomNo != "") {
            this.queryRoom();
          } else if (this.teacherNo != "") {
            this.queryTeacher();
          } else {
            this.getList();
          }

          this.listLoading = false;
        });
    },
    clearAdjustPick() {
      this.srcId = null;
      this.srcRow = -1;
      this.srcCol = -1;
      this.srcTimeslot = -1;
      this.destId = null;
      this.destRow = -1;
      this.destCol = -1;
      this.destTimeslot = -1;
      this.recommendDest = []
    },
    // 查看与本id有冲突的个体
    getConfilctList(id) {
      this.$axios
        .get("/timetable/getConfilctList/" + id, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          let list = res.data.data;
          if (list.length == 0) {
            this.$message({ message: "不存在冲突", type: "info" });
          } else {
            let html = "本节课存在的冲突有："
            for (var i in list) {
              html += "<br/>" +list[i].conflictType
            }
            this.$alert(html , "提示", {
              confirmButtonText: "确定",
              dangerouslyUseHTMLString: true
            });
          }
          this.listLoading = false;
        });
    },
    // 排练
    rehearsalChangeTimeslot(id) {
      this.$axios
        .get("/timetable/rehearsalChangeTimeslot/" + id, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          let data = res.data.data;
          this.recommendDest = data
          // this.$alert("调课后不存在冲突的timeslot有：" + data, "提示", {
          //   confirmButtonText: "确定",
          // });

          // this.$message({message:'', type:'info'})
          this.listLoading = false;
        });
    },
    timeslotConvert(timeslot) {
      var week = Math.floor(timeslot / 5) + 1;
      let section =
        "(" + ((timeslot % 5) * 2 + 1) + "-" + ((timeslot % 5) * 2 + 2) + "节)";
      return "周" + week + section;
    },
    initClassTableData() {
      this.classTableData = {
        lessons: [
          "08.20-09.55",
          "10.15-11.50",
          "14.20-15.55",
          "16.15-17.50",
          "18.30-20.05",
        ],
        courses: [[], [], [], [], [], [], []],
        timetableId: [[], [], [], [], [], [], []],
        timeslot: [[], [], [], [], [], [], []],
      };
      return true;
    },
    setToTable(ret) {
      if (!this.initClassTableData()) {
        // console.log('initClassTableData失败', this.classTableData)
        return;
      } else {
        // console.log('initClassTableData成功',this.classTableData)
      }

      let level = 0;
      let times = 0;
      let index = 0;
      let beforeTimeslot = -1;
      let flag = false; // flag为true表示 全空
      let sameTimeslotIndex = 0;
      if (this.classNo == "" && this.roomNo == "" && this.teacherNo == "") {
        flag = true;
      }
      if (this.semesterId == null) {
        flag = true;
      }
      for (let timess = 0; timess < 35; timess++) {
        const item = ret[index];
        if (!flag && item != undefined && beforeTimeslot == item.timeslot) {
          timess--;
        }
        level = Math.floor(timess / 5);
        if (flag || index >= ret.length || parseInt(item.timeslot) != timess) {
          // 添加空字符串表示没有课程
          this.classTableData.courses[level].push("");
          this.classTableData.timetableId[level].push(-1);
          this.classTableData.timeslot[level].push(timess);
          index = index - 1;
        } else {
          let section =
            "(" +
            ((item.timeslot % 5) * 2 + 1) +
            "-" +
            ((item.timeslot % 5) * 2 + 2) +
            "节)";
          let biweekly =
            item.biweekly == 1 ? "(单)" : item.biweekly == 2 ? "(双)" : "";
          let time =
            section + item.startWeek + "-" + item.endWeek + "周" + biweekly;
          let className = item.className;
          let teacherName = item.teacherName;
          let roomName = item.roomName
          let course = item.courseNo + "-" + item.courseName;
          let size = item.size;

          let msg =
            time +
            "/" +
            className +
            "/" +
            teacherName +
            "/" +
            roomName +
            "/" +
            course +
            "/" +
            "选课人数：" +
            size;

          if (beforeTimeslot != item.timeslot) {
            sameTimeslotIndex = 0;

            this.classTableData.courses[level].push(msg);
            this.classTableData.timetableId[level][item.timeslot % 5] = item.id;
            this.classTableData.timeslot[level].push(item.timeslot);
          } else {
            sameTimeslotIndex++;

            let oldmsg = this.classTableData.courses[level][item.timeslot % 5];
            this.classTableData.courses[level][item.timeslot % 5] =
              oldmsg + "@@@" + msg;
            let oldid =
              this.classTableData.timetableId[level][item.timeslot % 5];
            this.classTableData.timetableId[level][item.timeslot % 5] =
              oldid + "@@@" + item.id;
          }

          beforeTimeslot = item.timeslot;
        }
        times = times + 1;
        index++;
      }

      if (ret.length == 0) {
        this.$message({ message: "暂无课表", type: "success" });
      }
      console.log('classTableData', this.classTableData);
    },
    getList() {
      this.listLoading = true;
      this.classTableData.courses.forEach((item, index) => {
        item.length = 0; // 直接将数组长度设置为0来清空数组
      });
      this.$axios
        .get("/timetable/getList/" + this.semesterId, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          let ret = res.data.data;
          this.setToTable(ret);
          this.listLoading = false;
        });
    },
    // 根据班级查询课表
    queryClass() {
      this.listLoading = true;
      this.classTableData.courses.forEach((item, index) => {
        item.length = 0; // 直接将数组长度设置为0来清空数组
      });
      this.$axios
        .get("/timetable/class/" + this.semesterId + "/" + this.classNo)
        .then((res) => {
          let ret = res.data.data;
          this.setToTable(ret);
          this.listLoading = false;
        });
    },
    queryRoom() {
      this.listLoading = true;
      this.classTableData.courses.forEach((item, index) => {
        item.length = 0; // 直接将数组长度设置为0来清空数组
      });
      this.$axios
        .get("/timetable/room/" + this.semesterId + "/" + this.roomNo)
        .then((res) => {
          let ret = res.data.data;
          this.setToTable(ret);
          this.listLoading = false;
        });
    },
    queryTeacher() {
      this.listLoading = true;
      this.classTableData.courses.forEach((item, index) => {
        item.length = 0; // 直接将数组长度设置为0来清空数组
      });
      this.$axios
        .get("/timetable/teacher/" + this.semesterId + "/" + this.teacherNo)
        .then((res) => {
          let ret = res.data.data;
          this.setToTable(ret);
          this.listLoading = false;
        });
    },
    //获得班级列表
    getClass() {
      this.listLoading = true;
      this.$axios
        .get("/classes/getList")
        .then((res) => {
          let ret = res.data.data;
          for (let index = 0; index < ret.length; index++) {
            const item = ret[index];
            this.classData[index] = item;
          }
        })
        .catch((error) => {
          console.log("查询班级失败");
        });
    },
    getTeacher() {
      this.listLoading = true;
      this.$axios
        .get("/teacher/getList")
        .then((res) => {
          let ret = res.data.data;
          for (let index = 0; index < ret.length; index++) {
            const item = ret[index];
            this.teacherData[index] = item;
          }
        })
        .catch((error) => {
          console.log("查询班级失败");
        });
    },
    getRoom() {
      this.listLoading = true;
      this.$axios
        .get("/room/getList")
        .then((res) => {
          let ret = res.data.data;
          for (let index = 0; index < ret.length; index++) {
            const item = ret[index];
            this.roomData[index] = item;
          }
        })
        .catch((error) => {
          console.log("查询班级失败");
        });
    },
    //获得学期列表
    getSemester() {
      this.listLoading = true;
      this.$axios
        .get("/semester/getList")
        .then((res) => {
          let ret = res.data.data;
          for (let index = 0; index < ret.length; index++) {
            const item = ret[index];
            this.semesterData[index] = item;
          }
        })
        .catch((error) => {
          console.log("查询学期失败");
        });
    },
    /**
     * 数字转中文
     * @param {Number} num 需要转换的数字
     * @param {String} identifier 标识符
     * @returns {String} 转换后的中文
     */
    digital2Chinese(num, identifier) {
      const character = [
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        // "七",
        // "八",
      ];
      return identifier === "week" && (num === 0 || num === 7)
        ? "日"
        : character[num];
    },
    // 清除班级、教室、教师
    clearListener() {
      this.classNo = "";
      this.roomNo = "";
      this.teacherNo = "";
    },
    // 得到对应选中的班级
    handleSelectClass(val) {
      // 这里的val就是选择的班级了
      this.classNo = val;
      this.roomNo = "";
      this.teacherNo = "";
      this.clearAdjustPick();
      this.queryClass();
    },
    // 得到对应选中的教室
    handleSelectRoom(val) {
      // 这里的val就是选择的班级了
      this.roomNo = val;
      this.classNo = "";
      this.teacherNo = "";
      this.clearAdjustPick();
      this.queryRoom();
    },
    // 得到对应选中的教师
    handleSelectTeacher(val) {
      // 这里的val就是选择的班级了
      this.teacherNo = val;
      this.classNo = "";
      this.roomNo = "";
      this.clearAdjustPick();
      this.queryTeacher();
    },
    handleSizeChange(val) {
      this.pagesize = val;
      console.log(`每页 ${val} 条`);
    },
  },
};
</script>
<style scoped>
.mycard {
  position: relative;
  padding: 5px;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 5px;
}
.mycard:hover {
  box-shadow: 2px 5px 5px rgba(0, 0, 0, 0.1);
  background-color: #f5f7fa;
}
.span {
  display: block;
  color: white;
  height: 20px;
  text-align: center;
  line-height: 20px;
  border-radius: 5px;
}
.course-info {
  position: relative;
  white-space: pre-wrap; /* 保留空白和换行 */
}
.class-select {
  padding-left: 30px;
}
</style>
